package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"video/models"
	"video/util"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username") // chihao
	password := c.GetString("password") // 123456
	lockKey := "lock-" + username       //冻结
	countKey := "count-" + username     //记录密码错误次数
	num, _ := models.Rdb.Exists(lockKey).Result()
	if num > 0 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "账号1⃣️锁定",
		}
		c.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error //select * from users where username = 'chihao'
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "用户名错误",
		}
		c.ServeJSON()
		return
	}
	if user.Password == util.Md5Pwd(password) {
		models.Rdb.Del(lockKey)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "登录成功", //要记录用户状态（下发令牌）
		}
		c.ServeJSON()
		return
	} else {

		count, _ := models.Rdb.Get(countKey).Result()
		if count >= "3" {
			models.Rdb.Set(lockKey, "locked", time.Hour*24)
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "账号1⃣️锁定",
			}
			c.ServeJSON()
			return
		}
		models.Rdb.Incr(countKey) //密码错误次数+1
		models.Rdb.Expire(countKey, time.Hour*24)
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "密码错误",
		}
		c.ServeJSON()
		return
	}

}
